package cn.lixin;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginZuulFilter extends ZuulFilter {
    /**
     * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
     * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
     * We also support a "static" type for static responses see  StaticResponseFilter.
     * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)
     *
     * @return A String representing that type
     *
     * pre类型
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * filterOrder() must also be defined for a filter. Filters may have the same  filterOrder if precedence is not
     * important for a filter. filterOrders do not need to be sequential.
     *
     * @return the int order of a filter
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * a "true" return from this method means that the run() method should be invoked
     *
     * @return true if the run() method should be invoked. false will not invoke the run() method
     */
    @Override
    public boolean shouldFilter() {
        // 获取请求-判断是否是 登录或注册-不是返回true调用run方法
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("/login") || uri.endsWith("/register")) {
            return false;
        }
        return true;
    }

    /**
     * if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter
     *
     * @return Some arbitrary artifact may be returned. Current implementation ignores it.
     * @throws ZuulException if an error occurs during execution.
     */
    @Override
    public Object run() throws ZuulException {
        // 判读是否登录-没有登录返回错误信息
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
            try (PrintWriter writer = response.getWriter();)
            {
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                Map map = new HashMap();
                map.put("success","false");
                map.put("message","Nologin");
                //把map转成json字符串，写到浏览器
                Object json = JSON.toJSONString(map);
                writer.print(json);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);// 401状态码
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 阻止
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
